﻿using NB.MGJ.Common.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;

namespace NB.MGJ.Common.API
{
    public class ApiResult : IHttpActionResult
    {
        object _value;
        HttpRequestMessage _request;
        HttpStatusCode _statusCode;

        public ApiResult(object value, HttpRequestMessage request)
        {
            _value = value;
            _request = request;
            _statusCode = System.Net.HttpStatusCode.OK;
        }

        public ApiResult(object value, HttpRequestMessage request, HttpStatusCode statusCode)
        {
            _value = value;
            _request = request;
            _statusCode = statusCode;
        }

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
        {
            if (_value != null && _value.GetType() == typeof(string))
            {
                var response = new HttpResponseMessage()
                {
                    Content = new StringContent(_value.ToString()),
                    RequestMessage = _request,
                    StatusCode = HttpStatusCode.OK
                };
                return Task.FromResult(response);
            }
            else
            {
                var response = new HttpResponseMessage()
                {
                    Content = new StringContent(JsonConvert.SerializeObject(_value, new JsonSerializerSettings() { ContractResolver = new NullToEmptyStringResolver(), DateFormatString = "yyyy-MM-dd HH:mm:ss" })),
                    //Content = new StringContent(JsonConvert.SerializeObject(_value, new JsonSerializerSettings() { NullValueHandling= NullValueHandling.Ignore })),
                    RequestMessage = _request,
                    StatusCode = HttpStatusCode.OK
                };
                return Task.FromResult(response);
            }
        }
    }
}
